package com.ruoyi.service.contract.controller;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.file.domain.ContractFile;
import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.service.contract.client.FileClient;
import com.ruoyi.service.contract.domain.ContractInfo;
import com.ruoyi.service.contract.service.IContractInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * contractController
 * 
 * @author zhangpu
 * @date 2024-04-17
 */
@RestController
@Slf4j
@RequestMapping("/contract")
public class ContractInfoController extends BaseController
{
    @Autowired
    private IContractInfoService contractInfoService;

    @Autowired
    private FileClient fileClient;

    /**
     * 查询contract列表
     */
    @RequiresPermissions("contract:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(ContractInfo contractInfo)
    {
        startPage();
        List<ContractInfo> list = contractInfoService.selectContractInfoList(contractInfo);
        return getDataTable(list);
    }

    /**
     * 导出contract列表
     */
    @RequiresPermissions("contract:contract:export")
    @Log(title = "contract", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractInfo contractInfo)
    {
        List<ContractInfo> list = contractInfoService.selectContractInfoList(contractInfo);
        ExcelUtil<ContractInfo> util = new ExcelUtil<ContractInfo>(ContractInfo.class);
        util.exportExcel(response, list, "contract数据");
    }

    /**
     * 获取contract详细信息
     */
    @RequiresPermissions("contract:contract:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(contractInfoService.selectContractInfoById(id));
    }

    /**
     * 新增contract
     */
    @RequiresPermissions("contract:contract:add")
    @Log(title = "contract", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractInfo contractInfo)
    {
        return toAjax(contractInfoService.insertContractInfo(contractInfo));
    }

    /**
     * 修改contract
     */
    @RequiresPermissions("contract:contract:edit")
    @Log(title = "contract", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractInfo contractInfo)
    {
        log.info("修改合同");
        System.out.println(contractInfo);
        return toAjax(contractInfoService.updateContractInfo(contractInfo));
    }

    /**
     * 删除contract
     */
    @RequiresPermissions("contract:contract:remove")
    @Log(title = "contract", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(contractInfoService.deleteContractInfoByIds(ids));
    }


    @PostMapping("/uploadContract")
    public AjaxResult AjaxResult(MultipartFile file,ContractFile contractFile){
        log.info("上传合同");
        System.out.println("不可能吧");
        System.out.println(file.getOriginalFilename());
        String trueName = file.getOriginalFilename();
        String ext = FilenameUtils.getExtension(trueName);
        trueName = System.currentTimeMillis() + (long)(new Random()).nextInt(10000) + "." + ext;
        String affixPath = "D://nccqFile//" + trueName;
        File saveFile = new File(affixPath);
        if (!saveFile.exists()) {
            try {
                saveFile.createNewFile();
//                file.transferTo(saveFile);
                FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (ext.equals("doc") || ext.equals("docx") || ext.equals("xls") || ext.equals("xlsx") || ext.equals("ppt") || ext.equals("pptx")) {

            String _affixPath = affixPath.substring(0, affixPath.lastIndexOf(".")) + ".pdf";
            String officeHome = this.getOfficeHome();
//            d.office2Pdf(affixPath, _affixPath, officeHome);
//            filePath = filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf";

            try {
                // 启动OpenOffice连接
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
                connection.connect();

                // 创建转换器
                DocumentConverter converter = new OpenOfficeDocumentConverter(connection);

                // 执行转换
                File inputFile = new File(affixPath);
                File outputFile = new File(_affixPath);
                converter.convert(inputFile, outputFile);

                System.out.println("转换完成!");

                // 关闭连接
                connection.disconnect();
            } catch (ConnectException e) {
                System.err.println("无法连接到OpenOffice服务，请确保OpenOffice正在以-headless模式运行并监听指定端口。");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String sourcePath = "path/to/your/source.docx"; // Word文件路径
        String targetPath = "path/to/your/target.pdf"; // 目标PDF文件路径
        System.out.println(fileClient.test());
        contractFile.setId(UUID.randomUUID().toString().replace("-", ""));
        System.out.println(contractFile.getContractNo());
        contractFile.setFilePath(affixPath);
        contractFile.setFileName(trueName);
        contractFile.setFileSize(String.valueOf(file.getSize()));
        contractFile.setViewPath(trueName.substring(0,trueName.indexOf(".")) + ".pdf");
        contractFile.setCreateDate(DateUtils.getTime());
        System.out.println(contractFile.getCreateDate());
        AjaxResult result = fileClient.add(contractFile);


        try {
            FileUploadUtils.upload("D://nccqFile",file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return toAjax(1);

    }

    public String getOfficeHome() {
//        String osName = System.getProperty("os.name");
//        System.out.println("操作系统名称:" + osName);
//        if (Pattern.matches("Linux.*", osName)) {
//            return this.sysConfig.getOpenOffice().getLinuxPath();
//        } else if (Pattern.matches("Windows.*", osName)) {
//            return this.sysConfig.getOpenOffice().getWindowsPath();
//        } else {
//            return Pattern.matches("Mac.*", osName) ? this.sysConfig.getOpenOffice().getMacPath() : null;
//        }
        return "C:/Program Files (x86)/OpenOffice 4";
    }


    @GetMapping("/searchContractFile/{contractNo}")
    public AjaxResult SearchContractFile(@PathVariable String contractNo){
        log.info("根据合同编号查询附件");
        System.out.println(contractNo);
        List<ContractFile> contractFileList = fileClient.searchContractFile(contractNo);
        return AjaxResult.success(contractFileList);
    }
}
